import random

from facade.loggerfacade import get_streamlogger
from facade.mysqlfacade import MysqlUtiles
from xjlibrary.mrequest.baserequest import USER_AGENTS
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")

BookBaseUrl = "https://pubs.acs.org"

HEADERS = {'User-Agent': random.choice(USER_AGENTS)}

keytransformdicts = {"port": "db_port", "host": "db_host", "passwd": "db_pw", "user": "db_user",
                     "db": "db_name",
                     "chartset": "db_charset"}

logger = get_streamlogger()
myutil = MysqlUtiles(configfile, "db", keytransformdicts=keytransformdicts, logger=logger)


def nullcover():
    sql = "select `provider_url` from `modify_title_info_zt` WHERE cover='' or cover is Null"
    rows = myutil.SelectFromDB(sql)
    return rows


if __name__ == "__main__":
    urllist = []
    rows = nullcover()
    if rows:
        for row in rows:
            url = row[0].replace("acsbook@https://pubs.acs.org", "")
            urllist.append(url)
    sql = "select url,coverstat from ebook where coverstat=1 and url in {}".format(tuple(urllist))
    rows2 = myutil.SelectFromDB(sql)
    urllist.clear()
    for row in rows2:
        name = row[0].replace("/isbn/", "")
        coverpath = "/smartlib/acsbook/{}.jpg".format(name)
        url1 = "acsbook@https://pubs.acs.org"+row[0]
        sql = "update modify_title_info_zt set cover='{}' where `provider_url`='{}'".format(coverpath,url1)
        urllist.append(sql)
    myutil.ExeSqlListToDB(urllist,errExit=True)
    myutil.close()


